import gzip
import json
import time
from urllib import request

import requests


def construct_api(user_id, _rticket, ts, sec_user_id):
    """
    api 构造函数
    :param user_id: 用户的id
    :param _rticket: 时间戳
    :param ts: 时间戳
    :param sec_user_id: 用户的加密的id
    :return: api
    """
    api = "https://aweme-eagle.snssdk.com" \
          "/aweme/v1/user/?" \
          "user_id={}" \
          "&retry_type=no_retry" \
          "&iid=2480937513012510" \
          "&device_id=69979219212" \
          "&ac=wifi&channel=wandoujia_aweme1" \
          "&aid=1128&app_name=aweme" \
          "&version_code=630" \
          "&version_name=6.3.0" \
          "&device_platform=android" \
          "&ssmix=a&device_type=Redmi+K20+Pro+Premium+Edition" \
          "&device_brand=Xiaomi&language=zh" \
          "&os_api=29&os_version=10" \
          "&openudid=199a04a384a330c1" \
          "&manifest_version_code=630" \
          "&resolution=1080*2210" \
          "&dpi=440&update_version_code=6302" \
          "&_rticket={}" \
          "&mcc_mnc=46011" \
          "&js_sdk_version=1.16.3.5" \
          "&ts={}" \
          "&sec_user_id={}" \
          "".format(user_id, _rticket, ts, sec_user_id)
    return api


def construct_header(user_id, sec_user_id, cookie, query, token, user_agent, _rticket, ts):
    """
    构造请求头，需要传入的参数如下
    :param user_id: 要爬取的用户的uid
    :param sec_user_id: 要爬取的用户的加密的id
    :param cookie: cookie
    :param query: 请求的query
    :param token: 你的token
    :param user_agent: 请求的user_agent
    :param _rticket: 时间戳（毫秒级）
    :param ts: 时间戳（秒级）
    :return: 构造好的请求头：headers
    """
    api = construct_api(user_id, _rticket, ts, sec_user_id)

    headers = {
        "Host": "aweme-eagle.snssdk.com",
        "Connection": "keep-alive",
        "Cookie": cookie,
        "Accept-Encoding": "gzip",
        "X-SS-QUERIES": query,
        "X-SS-REQ-TICKET": _rticket,
        "X-Tt-Token": token,
        "sdk-version": "1",
        "User-Agent": user_agent
    }
    headers["X-Khronos"] = ts
    x_gorgon = get_gorgon(api, headers)
    headers["X-Gorgon"] = x_gorgon
    # print(headers)
    return headers


def get_gorgon(api, headers):
    '''
    获取gorgon的方法
    :param api: 抖音的api请求
    :param headers: 抖音的header请求
    :return: gorgon
    '''
    gorgon_host = "http://106.12.205.72:8080/gorgon"
    headers['api'] = api
    res = requests.get(gorgon_host, headers=headers)
    # 因为后面爬取数据还要用到headers，所以我们在获取到gorgon之后要把headers里面的api字段给它去掉
    del headers['api']
    # print("gorgon-status: ", res.status_code)
    res = json.loads(res.content)
    # print(res.keys())
    gorgon = res.get("gorgon")
    # print(res['status'])
    if res['status'] == '0':
        # print("gorgon:", gorgon)
        pass
    else:
        print("获取gorgon失败，失败原因是:")
        print(res['msg'])
    return gorgon


def get_user_detail_info(cookie, query, token, user_agent, user_id, sec_user_id):
    """
    爬取用户数据
    :param cookie: 你自己的cookie
    :param query: 你自己的query
    :param token: 你自己的token
    :param user_agent: 你自己的User-Agent
    :param user_id: 用户的uid
    :param sec_user_id: 用户的加密的uid
    :return: response
    """
    _rticket = str(time.time() * 1000).split(".")[0]
    ts = str(time.time()).split(".")[0]

    api = construct_api(user_id, _rticket, ts, sec_user_id)
    headers = construct_header(user_id, sec_user_id, cookie, query, token, user_agent, _rticket, ts)
    # print(api)
    req = request.Request(api)
    for key in headers:
        req.add_header(key, headers[key])

    with request.urlopen(req) as f:
        data = f.read()
    return gzip.decompress(data).decode()
